<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { userUpdatePasswordService } from '@/api/user.js'
// 定义数据
const formRef = ref()
// 是在使用仓库中数据的初始值（无需响应式）解构无问题
const formModel = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
// 表单校验
const checkOldSame = (rule, value, callback) => {
  // 校验新密码和原密码不能一样
  if(value === formModel.value.old_pwd) {
    callback(new Error('原密码和新密码不能一样!'))
  } else {
    callback()
  }
}
const checkSameAsNewPwd = (rule, value, callback) => {
  if(value !== formModel.value.new_pwd) {
    callback(new Error('新密码和确认再次输入的新密码不一样!'))
  } else {
    callback()
  }
}
const rules = {
  old_pwd: [
    {required: true, message: '请输入原密码', trigger: 'blur'},
    {min: 6, max: 15, message: '原密码必须是6-15位的非空字符', trigger: 'blur'}
  ],
  new_pwd: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 15, message: '新密码必须是6-15位的非空字符', trigger: 'blur'},
    {validator: checkOldSame, trigger: 'blur'}
  ],
  re_pwd: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {min: 6, max: 15, message: '确认新密码必须是6-15位的非空字符', trigger: 'blur'},
    {validator: checkSameAsNewPwd, trigger: 'blur'}
  ]
}
// 点击提交
const userStore = useUserStore()
const router = useRouter()
const onSubmit = async () => {
  // 先校验是否成功 等待校验结果
  await formRef.value.validate()
  // 提交修改
  await userUpdatePasswordService(formModel.value)
  // 提示用户
  ElMessage.success('密码修改成功')
  // 密码修改成功后，退出重新登录
  // 清空本地存储的token和个人信息
  userStore.setToken('')
  userStore.setUser({})
  // 拦截登录
  router.push('/login')
}
// 点击重置
const onReset = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <PageContainer title="重置密码">
    <!--表单部分-->
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="120px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="formModel.old_pwd" placeholder="请输入原密码" show-password style="max-width: 260px;"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="formModel.new_pwd" placeholder="请输入新密码" show-password style="max-width: 260px;"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="formModel.re_pwd" placeholder="请再次输入新密码" show-password style="max-width: 260px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="onSubmit" type="primary">提交修改</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>

<style lang="scss" scoped>

</style>
